package com.tea.servlet;

import com.tea.dao.UserDao;
import com.tea.entity.User;
import com.tea.service.UserService;
import com.tea.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@MultipartConfig(maxFileSize = 5 * 1024 * 1024) // 5MB文件限制
public class RegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");

        // 空值校验
        if (password == null || confirmPassword == null) {
            req.setAttribute("error", "密码不能为空");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }
        String redirect = req.getParameter("redirect");

        // 基础验证
        if (!password.equals(confirmPassword)) {
            req.setAttribute("error", "密码与确认密码不一致");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        // 处理头像上传
        String avatarPath = null;
        try {
            Part avatarPart = req.getPart("avatar");
            if (avatarPart != null && avatarPart.getSize() > 0) {
            String uploadDir = req.getServletContext().getRealPath("/uploads");
        if (uploadDir == null) {
            uploadDir = req.getServletContext().getRealPath("/") + "uploads";
        }
        Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            if (avatarPart == null) {
                req.setAttribute("error", "请上传头像");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }
            String originalFileName = avatarPart.getSubmittedFileName();
            String fileExtension;
            if (originalFileName == null || originalFileName.lastIndexOf(".") == -1) {
                fileExtension = ".jpg"; // 默认扩展名
            } else {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String newFileName = UUID.randomUUID() + fileExtension;
            Path targetPath = uploadPath.resolve(newFileName);

            try (InputStream input = avatarPart.getInputStream()) {
                Files.copy(input, targetPath, StandardCopyOption.REPLACE_EXISTING);
            }
            avatarPath = "/uploads/" + newFileName;
        }
        } catch (IllegalStateException e) {
            req.setAttribute("error", "文件大小超过限制");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        } catch (ServletException | IOException e) {
            req.setAttribute("error", "文件上传失败: " + e.getMessage());
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        // 验证重定向地址安全性
        if (redirect != null && !redirect.startsWith(req.getContextPath())) {
            redirect = "/index.jsp";
        }

        // 保存用户到数据库
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAvatar(avatarPath);

        UserService userService = new UserServiceImpl();
        try {
            // 检查用户名是否已存在
            if (userService.checkUsernameExists(username)) {
                req.setAttribute("error", "用户名已存在");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }

            // 注册用户
            if (!userService.register(user)) {
                req.setAttribute("error", "注册失败，请重试");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            } else {
                // 注册成功后跳转首页
                resp.sendRedirect(redirect != null ? redirect : "/index.jsp");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}